/**
*
 * Written by Nicholas Hillier on Nov 28,2008
 * This requires Tweener to work
 * Self explanitory scroller object, that dispatches percentage positioning
 * through a Percentage event, also included in the Ghostmonk package 
 * You must move the target display object outside of this class by listening to percentage events
 *  
*/
package com.ghostmonk.ui
{
	import caurina.transitions.Tweener;
	
	import com.ghostmonk.events.PercentageEvent;
	import com.ghostmonk.shapes.InnerShadowRectangle;
	
	import flash.display.*;
	import flash.events.MouseEvent;
	
	[Event(name="change", type="com.ghostmonk.events.PercentageEvent")]

	public class Scroller extends Sprite
	{
		private var _track:DisplayObject;
		private var _scrubHead:Sprite;
		private var _isVertical:Boolean;
		private var _bg:InnerShadowRectangle;
		
		//TODO: implement isVertical capability
		public function Scroller(track:DisplayObject, scrubHead:Sprite, isVertical:Boolean = true)
		{
			_track = track;
			_scrubHead = scrubHead;
			_isVertical = isVertical;
			layout();
			addChild(_track);
			addChild(_scrubHead);
			
			_bg = new InnerShadowRectangle(0,width,height);
			_bg.alpha = 0;
			addChildAt(_bg, 1);
			buttonMode = true;
			_scrubHead.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			_bg.addEventListener(MouseEvent.CLICK, onClick);
		}
		
		public function abort():void
		{
			onMouseUp(null);
		}
		
		private function onClick(e:MouseEvent):void
		{
			var time:Number = Math.abs(_scrubHead.y-mouseY)/(height-_scrubHead.height);
			Tweener.addTween(_scrubHead,{y:calcMouseY(), time:time , onUpdate:dispatchChange });
		}
		
		private function onMouseDown(e:MouseEvent):void
		{
			stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
		}
		
		private function onMouseUp(e:MouseEvent):void
		{
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
		}
		
		private function onMouseMove(e:MouseEvent):void
		{
			_scrubHead.y = calcMouseY();
			dispatchChange();
		}
		
		private function dispatchChange():void
		{
			var percent:Number = _scrubHead.y/(_track.height - _scrubHead.height);
			dispatchEvent(new PercentageEvent(PercentageEvent.CHANGE, percent));
		}
		
		private function calcMouseY():Number
		{
			return Math.max(0, Math.min(mouseY, _track.height - _scrubHead.height));
		}
		
		private function layout():void
		{
			if(_scrubHead.width >= _track.width)
			{
				_track.x = (_scrubHead.width - _track.width)/2;	
			}
			else
			{
				_scrubHead.x = (_track.width - _scrubHead.width)/2;
			}
			_scrubHead.y = 0;
		}
		
	}
}